//
//  DHTabBar.m
//  lotteryticket
//
//  Created by DH on 16/4/16.
//  Copyright © 2016年 http://blog.sina.com.cn/dhios All rights reserved.
//

#import "DHTabBar.h"
#import "DHTabBarButton.h"
#import "UIImage+DHAdd.h"

@interface DHTabBar()
@property (nonatomic, weak) DHTabBarButton *tempTabBarBtn;
@end

@implementation DHTabBar

- (instancetype)init
{
    if (self = [super init]) {
        self.backgroundColor = [UIColor blackColor];
        }
    
    return self;
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    for (int i = 0; i < self.subviews.count; i ++) {
        CGFloat w = self.bounds.size.width / self.subviews.count;
        CGFloat h = self.bounds.size.height;
        CGFloat y = 0;
        CGFloat x = w * i;
        DHTabBarButton *tabBarBtn = self.subviews[i];
        tabBarBtn.frame = CGRectMake(x, y, w, h);
    }
    
}

- (void)addTabBarBtnWithItem:(UITabBarItem *)item
{
    DHTabBarButton *tabBarBtn = [[DHTabBarButton alloc] init];
    
    // 设置一些基本属性
    tabBarBtn.titleLabel.font = [UIFont systemFontOfSize:11];
//    tabBarBtn setAttributedTitle:<#(nullable NSAttributedString *)#> forState:<#(UIControlState)#>
    tabBarBtn.tag = self.subviews.count;
    [tabBarBtn addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchDown];
    [self addSubview:tabBarBtn];
    if (item.image) {
        [tabBarBtn setImage:item.image forState:UIControlStateNormal];
    }
    if (item.selectedImage) {
        [tabBarBtn setImage:item.selectedImage forState:UIControlStateSelected];
    }
    [tabBarBtn setTitle:item.title forState:UIControlStateNormal];
    [tabBarBtn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    [tabBarBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [tabBarBtn setBackgroundImage:[UIImage createImageWithColor:DHRGB(253, 207, 42)] forState:UIControlStateSelected];
    [tabBarBtn setBackgroundImage:[UIImage createImageWithColor:[UIColor blackColor]] forState:UIControlStateNormal];
    
    if (self.subviews.count == 1)
    {
        [self tabBarButtonClick:tabBarBtn];
    }

}

- (void)tabBarButtonClick:(DHTabBarButton *)tabBarButton
{
    self.tempTabBarBtn.selected = NO;
    tabBarButton.selected = YES;
    if (self.btnClickHandler) {
        self.btnClickHandler(self, self.tempTabBarBtn.tag, tabBarButton.tag);
    }
    self.tempTabBarBtn = tabBarButton;
}

@end
